
#include <stdio.h>
#include <assert.h>

#include "js/util/util.h"
#include "js/core/core.h"
#include "js/sdl/sdl.h"

#include <v8.h>

using namespace v8;

static int start_v8(const char * file_name) {
    Context::Scope dummy_context(Context::New());

    // Create SDL application context
    js::bindings::sdl::SdlApp * app = js::bindings::sdl::create_sdl_app();

    // Create a stack-allocated handle scope.
    HandleScope handle_scope;

    // globally used definitions from the javascript code
    Handle<ObjectTemplate> globals = ObjectTemplate::New();

    // Add globals (binding forms)
    js::bindings::core::add_globals(globals);
    js::bindings::sdl::add_globals(globals, app);

    // Create a new context.
    Persistent<Context> context = Context::New(0, globals);

    // Enter the created context for compiling and
    // running the hello world script.
    Context::Scope context_scope(context);

    // Include main file
    js::run_js_script(file_name);

    // Run SDL application
    int result = js::bindings::sdl::run_sdl_app(app);

    // Dispose the persistent context.
    context.Dispose();

    // Free sdl application context
    js::bindings::sdl::free_sdl_app(app);
    return result;
}

int main(int argc, char ** argv) {
    const char * main_js_file_name = "../../js/samples/sdl/hello.js";

    if (argc > 1) {
        main_js_file_name = argv[1];
    }

    return start_v8(main_js_file_name);
}
